package com.ai.sml.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class WebUtils {

	protected static transient Log logger = LogFactory.getLog(WebUtils.class);
	public static final String SESSION_CONSOLE_USER = "SESSION_CONSOLE_USER";

	public static String escapeParamString(String valueIn) {
		String value = valueIn;
		if (valueIn == null)
			return "";
		
		value = StringUtils.replace(value, "|", "");
		value = StringUtils.replace(value, "&amp;", "");
		value = StringUtils.replace(value, ";", "");
		value = StringUtils.replace(value, "$", "");
		value = StringUtils.replace(value, "%", "");
		value = StringUtils.replace(value, "@", "");
		value = StringUtils.replace(value, "'", "");
		value = StringUtils.replace(value, "\"", "");
		value = StringUtils.replace(value, "\\'", "");
		value = StringUtils.replace(value, "&lt;", "");
		value = StringUtils.replace(value, "&gt;", "");
		value = StringUtils.replace(value, "<", "");
		value = StringUtils.replace(value, ">", "");
		value = StringUtils.replace(value, "(", "");
		value = StringUtils.replace(value, ")", "");
		value = StringUtils.replace(value, "+", "");
		value = StringUtils.replace(value, "\n", "");
		value = StringUtils.replace(value, "\r", "");
		value = StringUtils.replace(value, ",", "");
		value = StringUtils.replace(value, "\\", "");
		
		return value;
	}
	
    public static String toHTML(String valueIn) {
    	String value = valueIn;
        if (valueIn == null)
            return "";
        value = StringUtils.replace(value, "&", "&amp;");
        value = StringUtils.replace(value, "<", "&lt;");
        value = StringUtils.replace(value, ">", "&gt;");
        value = StringUtils.replace(value, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
        value = StringUtils.replace(value, "\r\n", "\n");
        value = StringUtils.replace(value, "\"", "&quot;");
        value = StringUtils.replace(value, "\n", "<br>");
        value = StringUtils.replace(value, "  ", "&nbsp;&nbsp;");
        value = StringUtils.replace(value, "'", "&#39;");
        value = StringUtils.replace(value, "\\", "&#92;");
        return value;
    }

	/**
	 * 获取当前时间
	 * @return java.sql.Date
	 */
	public static Date getCurrentDate(){
		return new Date(System.currentTimeMillis());
	}
	
	/**
	 * 获取当前操作人员IP
	 * @return "127.0.0.1"
	 */
	public static String getCurrentIP(HttpServletRequest request){
		String result = "";
		if (StringUtils.isBlank(result) || "unknown".equalsIgnoreCase(result)) {
			result = request.getHeader("x-forwarded-for");
		}
		if (StringUtils.isBlank(result) || "unknown".equalsIgnoreCase(result)) {
			result = request.getHeader("X-Forwarded-For");
		}
		if (StringUtils.isBlank(result) || "unknown".equalsIgnoreCase(result)) {
			result = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(result) || "unknown".equalsIgnoreCase(result)) {
			result = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(result) || "unknown".equalsIgnoreCase(result)) {
			result = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (StringUtils.isBlank(result) || "unknown".equalsIgnoreCase(result)) {
			result = request.getHeader("X-Real-IP");
		}
		if (StringUtils.isEmpty(result) || "unknown".equalsIgnoreCase(result) )
			result = request.getRemoteAddr();
		if ("127.0.0.1".equals(result) || "0:0:0:0:0:0:0:1".equals(result)) {
			InetAddress inet = null;
			try { // 根据网卡取本机配置的IP
				inet = InetAddress.getLocalHost();
			} catch (UnknownHostException e) {
				logger.error("getCurrentIP", e);
			}
			if (inet != null) {
				result = inet.getHostAddress();
			}
		}
		if (!StringUtils.isEmpty(result)) {
			if (result.indexOf(".") != -1){ // 没有"."肯定是非IPv4格式
				Pattern pat = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
				Matcher mat = pat.matcher(result);
				result = null;
				while (mat.find()) {
					result = mat.group(0);
					break;
				}
			}
			else
				result = null;
		}

		return result;
	}
	/**
	 * 获取当前操作人员LocalInstance
	 * @return "127.0.0.1"
	 */
	public static String getCurrentLocalInstance(HttpServletRequest request){
		return request.getServerName()+":"+request.getServerPort();
	}



	
	/**
	 * fckeditor 编辑后的 freemarker模板， <# > 标签以及里面的引号都会被替换成&lt;#    &gt; &quot;
	 * 这个方法的作用是把它恢复回来
	 * 
	 * ...结果没用到...
	 * @param s
	 * @return
	 */
	public static String restoreFreemarkerTag(String s){
		
		StringBuffer sb = new StringBuffer();
		
		Pattern p = Pattern.compile("&lt;#(.+?)&gt;");
		Matcher m = p.matcher(s);
		while(m.find()){
			String tmp = m.group(1);
			tmp = "<#" + StringUtils.replace(tmp, "&quot;", "\"") + ">";
			m.appendReplacement(sb, tmp);
		}
		m.appendTail(sb);
		return sb.toString();
	}
	
	/**
	 * reflection机制复制对象属性，必须有getter和setter方法对应才能复制
	 * @param obj1
	 * @param obj2
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static void copyProperty(Object srcObj, Object destObj)
			throws IllegalArgumentException, IllegalAccessException,
			InvocationTargetException {
		
		Method[] srcMethods = srcObj.getClass().getDeclaredMethods();
		Method[] destMethods = destObj.getClass().getDeclaredMethods();
		
		for (int i = 0; i < destMethods.length; i++) {
			//以set开头的方法，则取到属性名并用srcObj的get方法取属性值
			if (destMethods[i].isAccessible() && destMethods[i].getName().startsWith("set")) {
				String fieldName = destMethods[i].getName();
				fieldName = destMethods[i].getName().substring(3,fieldName.length());
				//从srcObj里找对应属性的get方法
				for (int j = 0; j < srcMethods.length; j++) {
					if (srcMethods[j].getName().equals("get" + fieldName)) {
						Object value = srcMethods[j].invoke(srcObj);
						destMethods[i].invoke(destObj, new Object[]{ value });
						break;
					}
				}
			}
		}
	}
	
	/**
	 * 创建指定数量的随机字符串
	 * 
	 * @param numberFlag
	 *            是否是数字
	 * @param length
	 * @return
	 */
	public static String createRandom(boolean numberFlag, int length) {
		String retStr;
		String strTable = numberFlag ? "1234567890"
				: "1234567890abcdefghijkmnpqrstuvwxyz";
		int len = strTable.length();
		boolean bDone = true;
		do {
			retStr = "";
			int count = 0;
			for (int i = 0; i < length; i++) {
				double dblR = Math.random() * len;
				int intR = (int) Math.floor(dblR);
				char c = strTable.charAt(intR);
				if (('0' <= c) && (c <= '9')) {
					count++;
				}
				retStr += Character.toString(strTable.charAt(intR));
			}
			if (count >= 2) {
				bDone = false;
			}
		} while (bDone);

		return retStr;
	}

}